//
//  CCAListViewController.m
//  Activity
//
//  Created by coco on 15/5/10.
//  Copyright (c) 2015年 coco. All rights reserved.
//

#import "CCAListViewController.h"
#import "CCAListTableViewCell.h"
#import "CCAListViewModel.h"
#import "MJRefresh.h"
#import "CCAListCellViewModel.h"
#import "CCProgressHUD.h"
#import "CCError.h"
#import "CCAcitivityModel.h"
#import <UITableView+FDTemplateLayoutCell/UITableView+FDTemplateLayoutCell.h>

@interface CCAListViewController ()
@property (nonatomic, strong) CCAListViewModel *viewModel;
@property (nonatomic, strong) UITableView *tableView;
@end

@implementation CCAListViewController
- (id) initWithViewModel:(CCAListViewModel *)viewModel {
  if ( self = [super init] ) {
    _viewModel = viewModel;
  }
  return self;
}
- (void)viewDidLoad {
  [super viewDidLoad];
  [self setupBar];
  [self getActivity];
}
- (void) viewDidAppear:(BOOL)animated {
  [super viewDidAppear:animated];
}

- (void) viewWillAppear:(BOOL)animated {
  self.hidesBottomBarWhenPushed = NO;
  [super viewWillAppear:animated];
}
- (void) viewDidDisappear:(BOOL)animated{
  [super viewDidDisappear:animated];
}

- (void) viewWillDisappear:(BOOL)animated {
  [super viewWillDisappear:YES];
}

- (void) getActivity {
  [CCProgressHUD showHUBInView:self.view withTimeOut:0 str:nil];
  [[self.viewModel locationCity] subscribeNext:^(id x) {
    [[_viewModel getActivity] subscribeNext:^(CCError *x) {
      if (x.code == 2002) {
        [self setupUI];
        [self setupRefresh];
        [self viewWithCSS];
        [self.tableView reloadData];
      } else {
        [CCProgressHUD showMessage:self.view withTimeOut:1.0f str:x.des];
        [self showErrorView:x.des block:^{
          [self getActivity];
          [self hiddenErrorView];
        }];
      }
      [CCProgressHUD hiddenHUBFromView:self.view];
    }];
    
  } error:^(NSError *error) {
    [[_viewModel getActivity] subscribeNext:^(CCError *x) {
      if (x.code == 2002) {
        [self setupUI];
        [self setupRefresh];
        [self viewWithCSS];
        [self.tableView reloadData];
      } else {
        [CCProgressHUD showMessage:self.view withTimeOut:1.0f str:x.des];
        [self showErrorView:x.des block:^{
          [self getActivity];
          [self hiddenErrorView];
        }];
      }
      [CCProgressHUD hiddenHUBFromView:self.view];
    }];    
  }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void) setupBar {
  RAC(self, title) = RACObserve(self.viewModel, viewTitleString);
  self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
  [self.navigationItem.leftBarButtonItem setTitleTextAttributes:@{NSForegroundColorAttributeName:RGB(255, 255, 255, 1)} forState:UIControlStateNormal];
  RAC(self.navigationItem.leftBarButtonItem, title) = RACObserve(self.viewModel, city);
}

- (void)setupUI {
  self.automaticallyAdjustsScrollViewInsets = YES;
   self.tableView = [[UITableView alloc] initWithFrame:CGRectZero
                                                 style:UITableViewStylePlain];
  [self.tableView registerClass:[CCAListTableViewCell class] forCellReuseIdentifier:@"cell"];
   self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
   self.tableView.backgroundColor = [UIColor colorWithRed:239/255.0f green:239/255.0f blue:243/255.0f alpha:1];
   [self.view addSubview:self.tableView];
   self.tableView.delegate = self;
   self.tableView.dataSource = self;
}

- (void) viewWithCSS {
  [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
    make.leading.equalTo(self.view);
    make.right.equalTo(self.view);
    make.bottom.equalTo(self.view);
    make.top.equalTo(self.view).offset(self.yoffset);
  }];
}

- (void)setupRefresh
{
  @weakify(self);
  [self.tableView addHeaderWithCallback:^{
    @strongify(self);
    [[self.viewModel getHeader] subscribeNext:^(id x) {
        [CCProgressHUD showMessage:self.view withTimeOut:1.0f str: [(CCError *)x des]];
        [self.tableView reloadData];
      [self.tableView headerEndRefreshing ];
    }];
  }];
  
  [self.tableView addFooterWithCallback:^{
    @strongify(self);
    [[self.viewModel getFoot] subscribeNext:^(id x) {
        [CCProgressHUD showMessage:self.view withTimeOut:1.0f str: [(CCError *)x des]];
        [self.tableView reloadData];
      [self.tableView footerEndRefreshing];
    }];
  }];
}

- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  CCAListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
  CCAListCellViewModel *viewModel = [[CCAListCellViewModel alloc] initWithData:
                                     self.viewModel.activityArray[indexPath.row]];
  [cell bindViewModel:viewModel];
  return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
  NSInteger count =  self.viewModel.activityArray.count;
  return count;
}

#pragma mark uitableview delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  return [tableView fd_heightForCellWithIdentifier:@"cell" configuration:^(id cell) {
    CCAListCellViewModel *viewModel = [[CCAListCellViewModel alloc] initWithData:
                                       self.viewModel.activityArray[indexPath.row]];
    [cell bindViewModel:viewModel];
  }];

}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  [CCRouter routerWithURL:@"detail" param:@{@"id":[(CCAcitivity *)self.viewModel.activityArray[indexPath.row] objectid],
                                            @"authorId":[(CCAcitivity *)self.viewModel.activityArray[indexPath.row]authorId]}];
}
@end
